package cn.bjc.rocketemq.consumer;

import cn.bjc.order.domain.OrderPetAcquisition;
import cn.bjc.order.mapper.OrderPetAcquisitionMapper;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "queue_test_topic",selectorExpression="*",consumerGroup = "queue_group_test")
public class RocketMQMsgListener implements RocketMQListener<MessageExt> {
    
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void onMessage(MessageExt message) {
        String msg = null;
        try {
            //从messsage中获取到msgBody,消息体
            byte[] body = message.getBody();
            //将byte转成String,设置编码
            msg = new String(body, CharsetUtil.UTF_8);
            //拿到OrderSn后,去查这个order信息
            OrderPetAcquisition order = orderPetAcquisitionMapper.loadByOrderSn(msg);

            //得到时间戳格式的时间,这是该订单预设值的过期时间
            long lastTime = order.getLastcomfirmtime().getTime();

            //得到系统现在当前时间的时间戳
            long newTime = System.currentTimeMillis();

            //判定订单
            //如果订单状态为0(-1:取消,0:等待接单),且已到或已超过)订单的过期时间
            if (order.getState()==0 && (newTime-lastTime)>0) {
                //设置订单订单状态为-1()已取消
                order.setState(-1);
                //写入数据库
                orderPetAcquisitionMapper.update(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        log.info("接收到消息：{}", msg);
    }

}
